﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Quartz.Spi;
using Quartz.Impl;
using HostedServiceDemo.EfContext;
using Microsoft.EntityFrameworkCore;

namespace HostedServiceDemo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var host = new HostBuilder()
                .ConfigureHostConfiguration(configHost =>
                {
                    // 配置根目录
                    configHost.SetBasePath(Path.GetDirectoryName(typeof(Program).Assembly.Location));
                    // 读取环境变量，Asp.Net core默认的环境变量是以ASPNETCORE_作为前缀的，这里也采用此前缀以保持一致
                    configHost.AddEnvironmentVariables("ASPNETCORE_");
                    // 读取启动host的时候之前可传入参数
                    configHost.AddCommandLine(args);
                })
                .ConfigureAppConfiguration((hostContext, configApp) =>
                {
                    // 读取应用的配置json
                    configApp.AddJsonFile("appsettings.json", true);
                    // 读取应用特定环境下的配置json
                    configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", true);
                    // 读取环境变量
                    configApp.AddEnvironmentVariables();

                })
                .ConfigureServices((hostContext, services) =>
                {
                    // 添加日志Service
                    services.AddLogging();

                    // 设置efcore连接字符串
                    services.AddDbContext<EFContext>(options => options.UseSqlite(hostContext.Configuration.GetConnectionString("demoConnection")));

                    services.AddSingleton<IJobFactory, JobFactory>();
                    services.AddSingleton(provider =>
                    {
                        StdSchedulerFactory factory = new StdSchedulerFactory();
                        var scheduler = factory.GetScheduler().ConfigureAwait(false).GetAwaiter().GetResult();

                        scheduler.JobFactory = provider.GetService<IJobFactory>();

                        return scheduler;
                    });
                    // 添加自定义的HostedService
                    services.AddHostedService<DBHostedService>();
                    services.AddHostedService<QuartzHostedService>();
                    services.AddSingleton<TestJob, TestJob>();
                })
                .ConfigureLogging((hostContext, configLogging) =>
                {
                    // 输出控制台日志
                    configLogging.AddConsole();
                    // 输出Debug日志
                    configLogging.AddDebug();
                })
                // 使用控制台生命周期
                .UseConsoleLifetime()
                .Build();
            await host.RunAsync();
        }
    }
}
